<?php
/**
 * Created by PhpStorm.
 * User: FDG296
 * Date: 2017/8/2
 * Time: 16:42
 */
namespace common\models;


use backend\models\Brand;
use common\helps\getActivityMessage;
use Yii;
use yii\db\ActiveRecord;

class GoodsSale extends ActiveRecord{

	const USE_FLG_YES	= 1;
	const USE_FLG_NO	= 0;


    public static function tableName(){
        return '{{%goods_sale}}';
    }

    /**
     * @获取创建人
     */
    public function getCreator(){
        $userInfo = \common\helps\tools::getloginUserInfo();
        if($userInfo){
            $userName = $userInfo->userName;
        }else{
            $userName = '';
        }
        return $userName;
    }

    //根据goods_id获取用户收藏商品列表
    public function getCustCollectionGoodsList($goods_id_list,$cust_id,$order = 'create_time desc',$search_keyword = ''){
        if(!empty($goods_id_list)){
            $where[] = 'and';
            $where[] = ['g.main_goods_id'=>$goods_id_list];
            $where[] = ['m.cust_id'=>$cust_id];
            if(!empty($search_keyword)){
                $where[] = ['like','g.goods_name_cn',$search_keyword];
            }
            $fields = 'g.id,g.main_goods_id,g.goods_id,g.sku,g.goods_name_cn,g.goods_name_other,g.market_price,g.hidden_price,
            g.sale_price,g.unit,g.goods_pic_title,g.goods_pic_alt,g.goods_main_pic,g.series,g.model,g.brand_id,g.brand_name,g.use_flg,m.create_time';
            $result = GoodsList::find()->where($where)->alias('g')->
            leftJoin('j_cust_favorite as m','g.main_goods_id = m.main_goods_id')->orderBy('m.'.$order)->select($fields)->asArray()->all();
        }
        if(empty($result)){
            $result = array();
        }else{
            foreach($result as &$res){
                $res['time_format'] = date('Y年m月d号', strtotime($res['create_time']));
                //add by huangzhao 20180116 456 【商城需求】商城所有界面商品价格的小数部分都不显示 start
                $res['market_price'] = number_format($res['market_price'],0);
                $res['sale_price'] = number_format($res['sale_price'],0);
                //add by huangzhao 20180116 456 【商城需求】商城所有界面商品价格的小数部分都不显示 end
            }
        }
        return $result;
    }

    //根据goods_id获取商品列表
    public function getGoodsList($goods_id_list){
        if(!empty($goods_id_list)){
            $where = ['goods_id'=>$goods_id_list,'use_flg'=>1];
            $fields = 'id,main_goods_id,goods_id,sku,goods_name_cn,goods_name_other,market_price,
            sale_price,unit,goods_pic_title,goods_pic_alt,goods_main_pic,series,model,brand_name,use_flg,create_time';
            $result = $this::find()->where($where)->select($fields)->asArray()->all();
        }
        if(empty($result)){
            $result = array();
        }
        return $result;
    }

	/**
	 * @param $mainGoodsId main_good_id 主商品的id
	 * @return array|\yii\db\ActiveRecord[]
	 */
	public static function getMainGoodList($mainGoodsId){
		return self::find()
			->where([
				'main_goods_id'=>$mainGoodsId,
				'use_flg'=>self::USE_FLG_YES,
			])
			->asArray()
			->all();
	}

    //根据goods_id获取商品的规格，颜色，价格
    public function getGoodsListByMainId($main_goods_id){
        $where[] = 'and';
        $where[] = ['use_flg'=>1];
        if(!empty($main_goods_id)){
            $where[] = ['main_goods_id'=>$main_goods_id];
        }
        $result = $this::find()->where($where)->select('sku,series,model,goods_id,spec,spec_val,spec_color,spec_color_val,sale_price,market_price')->asArray()->all();
        if(empty($result)){
            $result = array();
        }
        return $result;
    }

    //根据goods_id获取商品的规格，颜色，价格
    public function getGoodsSpecByMainId($main_goods_id){
        $where[] = 'and';
        $where[] = ['use_flg'=>1];
        if(!empty($main_goods_id)){
            $where[] = ['main_goods_id'=>$main_goods_id];
        }
        $result = $this::find()->where($where)->select('spec')->asArray()->all();
        if(empty($result)){
            $result = array();
        }
        return $result;
    }

    //获取固定规格下的颜色规格
    public function getGoodsSpecColor($main_goods_id,$spec_format = 0){
        $where[] = 'and';
        $where[] = ['use_flg'=>1];
        if(!empty($main_goods_id)){
            $where[] = ['main_goods_id'=>$main_goods_id];
        }
        if(!empty($spec_format)){
            $where[] = ['spec'=>$spec_format];
        }
        $result = $this::find()->where($where)->select('spec_color')->asArray()->all();
        if(empty($result)){
            $result = array();
        }
        return $result;
    }

    //获取goods_id
    public function getGoodsId($main_goods_id,$spec,$spec_color = 0){
        $goods_id = '';
        $where = ['main_goods_id'=>$main_goods_id,'spec'=>$spec,'spec_color'=>$spec_color];
        $main_goods_list = $this::find()->where($where)->select('goods_id,id')->asArray()->one();
        if(!empty($main_goods_list)){
            $goods_id = $main_goods_list['goods_id'];
        }
        return $goods_id;
    }


	/**
	 * @param $main_goods_id
	 * @param $spec
	 * @param int $spec_color
	 * @return array|null|ActiveRecord
	 */
	public static  function getGoodsSaleInfo($main_goods_id,$spec=0,$spec_color = 0){
		$params = [
			'main_goods_id'	=>$main_goods_id,
			'spec'			=>$spec,
			'spec_color'	=>$spec_color,
			'use_flg'		=>self::USE_FLG_YES
		];
		$where	= array_filter($params);

		return self::find()
			->where($where)
			->asArray()
			->groupBy(['spec'])
			->all();
	}

    //获取sku列表
    public function getSkuList($main_goods_id,$spec,$spec_color){
        $sku_list = array();
        $where['main_goods_id'] = $main_goods_id;
        if(!empty($spec)){
            $where['spec'] = $spec;
        }
        if(!empty($spec_color)){
            $where['spec_color'] = $spec_color;
        }
        //$where = ['main_goods_id'=>$main_goods_id,'spec'=>$spec,'spec_color'=>$spec_color];
        $main_goods_list = $this::find()->where($where)->select('sku,id')->asArray()->all();
        if(!empty($main_goods_list)){
            $sku_list = array_column($main_goods_list,'sku');
        }
        return $sku_list;
    }
    
    //获取genre_type列表
    public function getGenreTypeList($main_goods_id,$spec,$spec_color){
        $genre_type = array();
        $where['main_goods_id'] = $main_goods_id;
        if(!empty($spec)){
            $where['spec'] = $spec;
        }
        if(!empty($spec_color)){
            $where['spec_color'] = $spec_color;
        }
        //$where = ['main_goods_id'=>$main_goods_id,'spec'=>$spec,'spec_color'=>$spec_color];
        $main_goods_list = $this::find()->where($where)->select('genre_type,id')->asArray()->all();
        if(!empty($main_goods_list)){
            $genre_type = array_filter(array_unique(array_column($main_goods_list,'genre_type')));
        }
        return $genre_type;
    }
    
    //获取goods_id列表
    public function getGoodsIdList($main_goods_id,$spec,$spec_color){
        $sku_list = array();
        $where['main_goods_id'] = $main_goods_id;
        if(!empty($spec)){
            $where['spec'] = $spec;
        }
        if(!empty($spec_color)){
            $where['spec_color'] = $spec_color;
        }
        //$where = ['main_goods_id'=>$main_goods_id,'spec'=>$spec,'spec_color'=>$spec_color];
        $main_goods_list = $this::find()->where($where)->select('goods_id,id')->asArray()->all();
        if(!empty($main_goods_list)){
            $sku_list = array_column($main_goods_list,'goods_id');
        }
        return $sku_list;
    }

    //获取商品图片和颜色图片集合
    public function getMainImage($main_goods_list){
        $main_goods_id = array_column($main_goods_list,'main_goods_id');
        $where = ['and',['main_goods_id'=>$main_goods_id],['use_flg'=>1],['!=','spec_color',0]];
        $list = $this::find()->where($where)->select('main_goods_id,goods_main_pic,goods_pic_title,goods_pic_alt,spec_color,goods_id')->asArray()->all();
        $result = $this->getArrayUniqueByKeys($list);

        //找到颜色图片
        $image = array();
        $goods_id = array_column($result,'goods_id');
        $image_list = $this::find()->where(['gs.goods_id'=>$goods_id])->alias('gs')->
                leftJoin('j_goods_spec as s','gs.spec_color = s.id')->select('gs.goods_id,s.img_url')->asArray()->all();
        foreach($image_list as $value){
            $image[$value['goods_id']] = $value['img_url'];
        }

        foreach($result as &$res){
            $res['img_url'] = $image[$res['goods_id']];
        }

        $data = array();
        foreach($result as $value){
            $data[$value['main_goods_id']][] = $value;
        }

        return $data;
    }

    function getArrayUniqueByKeys($arr)
    {
        $arr_out =array();
        foreach($arr as $k => $v)
        {
            $key_out = $v['main_goods_id']."-".$v['spec_color'];

            if(array_key_exists($key_out,$arr_out)){
                continue;
            }
            else{
                $arr_out[$key_out] = $arr[$k];
                $arr_wish[$k] = $arr[$k];
            }
        }
        return $arr_wish;
    }

	/**
	 * @param 根据主商品ID 获取相同规格 相同颜色的的商品
	 * @param 没有 $spec 和$specColor 返回售卖商品关联的信息
	 */
	public static function getIdenticalMainGoods($mainGoodsId,$spec='',$specColor=''){

		$params = [
			self::tableName().'.main_goods_id'	=>$mainGoodsId,
			//GoodsSpecRelation::tableName().'.main_goods_id'	=>$mainGoodsId,
			self::tableName().'.spec'			=>$spec,
			self::tableName().'.spec_color'	=>$specColor,
			self::tableName().'.use_flg'	=>self::USE_FLG_YES,
		];
		$where	= array_filter($params);

		//关联信息
		$relation	= '';
		if($spec){
			$relation	= 'specColorRelation';
		}

		if($specColor){
			$relation	= 'specRelation';
		}

		//add by FDG367 493 【商城需求】商品图片上增加图片打标 2018-02-02 start
		if(0< $specColor && 0 < $spec){
			$relation = 'markImgInfo';
		}
		//add by FDG367 493 【商城需求】商品图片上增加图片打标 2018-02-02 end
		return self::find()
			->where($where)
			->joinWith($relation)
			//->createCommand()->getRawSql();
			->asArray()
			->all();
	}

	/**
	 * @param 关联表信息 查询规格关联表（关联规格）
	 * @return \yii\db\ActiveQuery
	 */
	public function getSpecRelation(){
		return $this->hasOne(GoodsSpecRelation::className(),['spec_id'=>'spec']);
	}

	/**
	 * @param 关联表信息 查询规格关联表（关联颜色）
	 * @return \yii\db\ActiveQuery
	 */
	public function getSpecColorRelation(){
		return $this->hasOne(GoodsSpecRelation::className(),['spec_id'=>'spec_color','main_goods_id'=>'main_goods_id']);
	}

	/**
	 * @param 关联表信息 查询规格关联表（关联主商品） 查询所有商品的规格信息
	 * @param 售卖商品表缺少对应的规格主键ID
	 * @return \yii\db\ActiveQuery
	 */
	public function getMainSpecRelation(){
		return $this->hasOne(GoodsSpecRelation::className(),['main_goods_id'=>'main_goods_id']);
	}

	//add by FDG367 493 【商城需求】商品图片上增加图片打标 2018-02-02 start
	/**
	 * @return \yii\db\ActiveQuery获取打标扩展信息
	 */
	public function getMarkImgInfo(){
		return $this->hasOne(GoodsMarkingImg::className(),['id'=>'marking_img_id'])->andOnCondition([GoodsMarkingImg::tableName().'.use_flg'=>GoodsMarkingImg::STATUS_ENABLE]);
	}

	/**
	 * @param $mainGoodsId	根据sku获取对应的促销信息
	 * @return array
	 */
	public static function getGoodsActivityMessage($mainGoodsSku){
		//获取对应的信息
		$activity_model = new getActivityMessage();
		$cx_list = json_decode($activity_model->getActivityMessageData([$mainGoodsSku]),true);

		if($cx_list['code'] != 200){
			return [];
		}

		return $cx_list['data'];
		//获取商品促销扩展
	}

	//add by FDG367 493 【商城需求】商品图片上增加图片打标 2018-02-02 end
	public static function getGoodsIdInfo($goods_id,$useFlg=true){
		$filterWhere	= [
			'goods_id'=>$goods_id,
			'use_flg'=>$useFlg ? self::USE_FLG_YES : self::USE_FLG_NO
		];
		//mod by FDG367 如果传值为null不考虑商品的状态 545 【商城需求】心愿单页面有效商品删除后，可在撤销，原有效商品删除效果去除；可对失效商品全部删除 start
		if(null===$useFlg)
			$filterWhere = array_filter($filterWhere);

		return self::find()
			->select(['goods_id','main_goods_id','use_flg','sku'])
			->where($filterWhere)
			//->createCommand()->getRawSql();
			->asArray()
			->one();
	}

	/**
	 * @return \yii\db\ActiveQuery获取打标扩展信息
	 */
	public function getBrandInfo(){
		return $this->hasOne(GoodsBrand::className(),['id'=>'brand_id']);
	}

	/**
	 * @param $goods_id array|string goodssale/goods_id add FDG367 2018/03/28 562 心愿单数字显示有效商品的数字 start
	 * @param bool $useFlg 0：无效商品；1：有效商品
	 * @return int|string
	 */
	public static function getGoodsCount($goods_id,$useFlg=true){
		return self::find()
			->where([
				'goods_id'=>$goods_id,
				'use_flg'=>$useFlg ? self::USE_FLG_YES : self::USE_FLG_NO
			])
			->count();
	}

	/**
	 * @parma add by FDG367  所有项目572 【商城需求】Mobile首页整体调整 2018-04-10 start	 * @params 获取对应热卖商品main_goods_ids 集合
	 * @param array $genre_type
	 * @param array $sku
	 * @param bool $useFlg
	 * @return array|\yii\db\ActiveRecord[]
	 */
	public static function getMainGoodsIdInfo($genre_type=[],$sku=[],$useFlg=true){
		$filterWhere	=[
			'use_flg'=>$useFlg ? self::USE_FLG_YES : self::USE_FLG_NO
		];

		//mod by FDG367 如果传值为null不考虑商品的状态 545 【商城需求】心愿单页面有效商品删除后，可在撤销，原有效商品删除效果去除；可对失效商品全部删除 start
		if(null===$useFlg)
			$filterWhere = array_filter($filterWhere);

		return self::find()
			->select(['main_goods_id'])
			->where($filterWhere)
			->andWhere([
				'or',[
				'genre_type'=>$genre_type],
				['sku'=>$sku]
			])
			//->createCommand()->getRawSql();
			->asArray()
			->all();
	}
}